#include <iostream>
#include <FreeImage.h>
#include <glm/glm.hpp>

#include "TexturedSquare.h"
#include "variables.h"
TexturedSquare::TexturedSquare(GLuint ID)
{
	texID = ID;
}

TexturedSquare::TexturedSquare(const char* filename)
{
	texID = TexturedSquare::loadTexture(filename);
}

TexturedSquare::~TexturedSquare(void)
{
}

//this code is copy-pasted from some forum I dont remember where
GLuint TexturedSquare::loadTexture(const char* textureFile){
	GLuint texturaID;
	FREE_IMAGE_FORMAT formato = FreeImage_GetFileType(textureFile,0);//Automatocally detects the format(from over 20 formats!)
	FIBITMAP* imagen = FreeImage_Load(formato, textureFile);
 
	FIBITMAP* temp = imagen;
	imagen = FreeImage_ConvertTo32Bits(imagen);
	FreeImage_Unload(temp);
 
	int w = FreeImage_GetWidth(imagen);
	int h = FreeImage_GetHeight(imagen);
	std::cout <<"The size of the image is: "<<textureFile<<" es "<<w<<"*"<<h<< "\n"; //Some debugging code
 
	GLubyte* textura = new GLubyte[4*w*h];
	char* pixeles = (char*)FreeImage_GetBits(imagen);
	//FreeImage loads in BGR format, so you need to swap some bytes(Or use GL_BGR).
 
	for(int j= 0; j<w*h; j++){
		textura[j*4+0]= pixeles[j*4+2];
		textura[j*4+1]= pixeles[j*4+1];
		textura[j*4+2]= pixeles[j*4+0];
		textura[j*4+3]= pixeles[j*4+3];
		//cout<<j<<": "<<textura[j*4+0]<<"**"<<textura[j*4+1]<<"**"<<textura[j*4+2]<<"**"<<textura[j*4+3]<<endl;
	}
 
	//Now generate the OpenGL texture object 
 
	glGenTextures(1, &texturaID);
	glBindTexture(GL_TEXTURE_2D, texturaID);
	glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA, w, h, 0, GL_RGBA,GL_UNSIGNED_BYTE,(GLvoid*)textura );
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
 
	GLenum huboError = glGetError();
	if(huboError){
 
		std::cout<<"There was an error loading the texture"<< "\n";
	}
	return texturaID;
}

void TexturedSquare::draw( glm::mat4 global_transform){
		  glLoadIdentity();
		  glm::mat4 matx = glm::transpose( (this->transform)*(global_transform));
		  glLoadMatrixf(&matx[0][0]);

		  glUniform4fv(ambientcol ,1, this->ambient);
		  glUniform4fv(diffusecol ,1, this->diffuse );
		  glUniform4fv(specularcol ,1, this->specular );
		  glUniform4fv( emissioncol ,1, this->emission);
		  glUniform1f(shininesscol, this->shininess);
		  glUniform1i( textured_object, 1);

		  //glActiveTexture(GL_TEXTURE0);
		  glUniform1i( texture_location, 0);
		  glBindTexture( GL_TEXTURE_2D, this->texID);

		  glBegin(GL_QUADS);
			glTexCoord2f(1 ,1);
			glVertex3f(.5,.5,0);
			glTexCoord2f(0 ,1);
			glVertex3f(-.5,.5,0);
			glTexCoord2f(0 ,0);
			glVertex3f(-.5,-.5,0);
			glTexCoord2f(1 ,0);
			glVertex3f(.5,-.5,0);
		 glEnd();

		  glUniform1i( textured_object, 0);
}